package com.xpf.utils;


import com.xpf.annotations.FieldName;
import com.xpf.entity.FormDataDTO;
import com.xpf.service.process.entity.BpmStartDTO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * @desc:  蓝凌OA审批表单工具类
 * todo 参考代码（可以忽略）
 */
@Slf4j
public class LanDrayFormUtils {

    /**
     * 封装审批数据内容-通用
     * @param obj
     * @return
     */
    public static void setComponentValue(BpmStartDTO bpmStartDTO, Object obj) {
        List<FormDataDTO> formDataList = new ArrayList<>();
        if (obj == null ){
            return;
        }
        //获取class字节码
        Class<?> tClass = obj.getClass();
        Field[] tFields = getAllDeclaredFields(tClass.getDeclaredFields(),tClass);
        for (int i =0;i < tFields.length;i++){
            Field tField = tFields[i];
            // 获取注解的value值
            FieldName fieldNameAnnotation = tField.getAnnotation(FieldName.class);
            if (fieldNameAnnotation == null || StringUtils.isEmpty(fieldNameAnnotation.value())){
                continue;
            }
            // 获取实体对象的value值
            String val = (String)invokeMethod(tField,obj);
            //空值或空字符返回‘无’
            if((val == null || val.trim().isEmpty())){
                val = "无";
            }
            FormDataDTO vo = new FormDataDTO();
            vo.setLabel(fieldNameAnnotation.value());
            vo.setKey(tField.getName());
            vo.setValue(val);
            formDataList.add(vo);

        }
        bpmStartDTO.setFormData(formDataList);
    }

    public static Object invokeMethod(Field field, Object target) {
        try {
            PropertyDescriptor pd = new PropertyDescriptor(field.getName(), target.getClass());
            Method getMethod = pd.getReadMethod();//获得get方法
            return getMethod.invoke(target);
        } catch (Exception ex) {
//            log.info("Failed to class "+target.getClass().getName()+", problem: "+ex.getMessage());
        }
        return null;
    }

    public static Field[] getAllDeclaredFields(Field[] fields, Class<?> tClass) {
        Class<?> superclass = tClass.getSuperclass();
        if (superclass.equals(Object.class)){
            return fields;
        }
        Field[] supFields = superclass.getDeclaredFields();
        if (supFields.length == 0){
            return fields;
        }
        Field[] allFields = new Field[fields.length+supFields.length];
        System.arraycopy(fields,0,allFields,0,fields.length);
        System.arraycopy(supFields,0,allFields,fields.length,supFields.length);
        getAllDeclaredFields(allFields,superclass);
        return allFields;
    }
}
